# 客户档案管理页面
<script setup lang="ts">
// ----------------------- 导入相关依赖 -----------------------
// Vue 核心功能
import { nextTick, onMounted, onUnmounted, reactive, ref } from 'vue'
// Element Plus 组件和类型
import { ElMessage, FormInstance } from 'element-plus'
// Element Plus 图标
import { Search, Refresh, Plus, Edit, Delete, User, OfficeBuilding, Phone, Location, Document, InfoFilled } from '@element-plus/icons-vue'
// 自定义组件和hooks
import SysDialog from '@/components/dialog/SysDialog.vue'
import useDialog from '@/hooks/useDialog'
import useInstance from '@/hooks/useInstance'

// API相关
import {
  CompanyCustomer,
  CompanyCustomerListParam,
} from '@/api/companyCustomer/type'
import { addApi, editApi, deleteApi, getListApi } from '@/api/companyCustomer'

// ----------------------- 组件状态定义 -----------------------
// 获取全局实例和弹框方法
const { dialog, onShow, onClose } = useDialog()
const { global } = useInstance()

// 表格高度
const tableHeight = ref(0)

// 表格数据相关
const tableData = ref([]) // 表格数据
const loading = ref(false) // 加载状态
// 分页相关数据
const paginationData = reactive({
  total: 0,
  currentPage: 1,
  pageSize: 10,
})

// 查询表单对象
const searchForm = reactive<CompanyCustomerListParam>({
  companyName: undefined, // 公司名称
  companyCode: undefined, // 公司代码
  contactName: undefined, // 联系人
  page: 1, // 当前页
  limit: 7, // 每页条数
})

// 表单对象
const formData = reactive<CompanyCustomer>({
  id: undefined,
  companyName: undefined,
  companyCode: undefined,
  address: undefined,
  contactName: undefined,
  contactPhone: undefined,
  email: undefined,
  fax: undefined,
  notes: undefined,
})

// 表单验证规则
const rules = {
  companyName: [{ required: true, message: '请输入公司名称', trigger: 'blur' }],
  companyCode: [{ required: true, message: '请输入公司代码', trigger: 'blur' }],
  contactName: [
    { required: true, message: '请输入联系人姓名', trigger: 'blur' },
  ],
  contactPhone: [
    { required: true, message: '请输入联系人电话', trigger: 'blur' },
  ],
}

// 表单ref
const formRef = ref<FormInstance>()

// ----------------------- 方法定义 -----------------------
// 查询方法
const search = () => {
  paginationData.currentPage = 1
  getTableData()
}

// 重置查询条件
const reset = () => {
  searchForm.companyName = undefined
  searchForm.companyCode = undefined
  searchForm.contactName = undefined
  search()
}

// 获取表格数据
const getTableData = async () => {
  loading.value = true
  try {
    searchForm.page = paginationData.currentPage
    searchForm.limit = paginationData.pageSize
    const res = await getListApi(searchForm)
    if (res && res.data) {
      tableData.value = res.data.list
      paginationData.total = res.data.total
    }
  } catch (error) {
    console.error('获取表格数据失败:', error)
  } finally {
    loading.value = false
  }
}

// 打开新增对话框
const handleAdd = () => {
  dialog.title = '新增客户'
  dialog.width = 700
  dialog.height = 300
  Object.assign(formData, {
    id: undefined,
    companyName: undefined,
    companyCode: undefined,
    address: undefined,
    contactName: undefined,
    contactPhone: undefined,
    email: undefined,
    fax: undefined,
    notes: undefined,
  })
  onShow()
}

// 打开编辑对话框
const handleEdit = (row: CompanyCustomer) => {
  dialog.title = '编辑客户'
  dialog.width = 700
  dialog.height = 300
  Object.assign(formData, row)
  onShow()
}

// 删除
const handleDelete = async (id: number) => {
  const confirm = await global.$myConfirm('确定要删除该客户吗？')
  if (confirm) {
    try {
      await deleteApi(id)
      ElMessage.success('删除成功')
      // 如果当前页只有一条数据，删除后自动跳转到上一页
      if (tableData.value.length === 1 && paginationData.currentPage > 1) {
        paginationData.currentPage--
      }
      getTableData()
    } catch (error) {
      console.error('删除失败:', error)
    }
  }
}

// 关闭弹框
const closeDialog = () => {
  formRef.value?.resetFields()
  Object.assign(formData, {
    id: undefined,
    companyName: undefined,
    companyCode: undefined,
    address: undefined,
    contactName: undefined,
    contactPhone: undefined,
    email: undefined,
    fax: undefined,
    notes: undefined,
  })
  onClose()
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (formData.id) {
          await editApi(formData)
          ElMessage.success('编辑成功')
        } else {
          await addApi(formData)
          ElMessage.success('新增成功')
        }
        onClose()
        getTableData()
      } catch (error) {
        console.error('保存失败:', error)
      }
    }
  })
}

// 监听窗口大小变化
const handleResize = () => {
  nextTick(() => {
    tableHeight.value = window.innerHeight - 260
  })
}

// 生命周期钩子
onMounted(() => {
  getTableData()
  handleResize()
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
})
</script>

<template>
  <el-main class="customer-main">
    <div class="main-container">
      <!-- 搜索区域 -->
      <el-card class="search-card" shadow="hover">
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="公司名称">
            <el-input 
              v-model="searchForm.companyName" 
              placeholder="请输入公司名称" 
              clearable
              prefix-icon="OfficeBuilding"
            />
          </el-form-item>
          <el-form-item label="公司代码">
            <el-input 
              v-model="searchForm.companyCode" 
              placeholder="请输入公司代码" 
              clearable
              prefix-icon="Document"
            />
          </el-form-item>
          <el-form-item label="联系人">
            <el-input 
              v-model="searchForm.contactName" 
              placeholder="请输入联系人" 
              clearable
              prefix-icon="User"
            />
          </el-form-item>
          <el-form-item class="search-buttons">
            <el-button type="primary" @click="search" class="search-btn" :icon="Search">
              查询
            </el-button>
            <el-button @click="reset" class="reset-btn" :icon="Refresh">
              重置
            </el-button>
            <el-button type="success" @click="handleAdd" class="add-btn" :icon="Plus">
              新增
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 表格区域 -->
      <el-card class="table-card" shadow="hover">
        <el-table 
          v-loading="loading" 
          :data="tableData" 
          border 
          :height="tableHeight" 
          class="data-table"
          highlight-current-row
        >
          <el-table-column type="index" label="序号" width="70" align="center" />
          <el-table-column prop="companyName" label="公司名称" min-width="180" align="center" />
          <el-table-column prop="companyCode" label="公司代码" min-width="130" align="center" />
          <el-table-column prop="address" label="地址" min-width="200" align="center" show-overflow-tooltip />
          <el-table-column prop="contactName" label="联系人" min-width="100" align="center" />
          <el-table-column prop="contactPhone" label="联系电话" min-width="120" align="center" />
          <el-table-column prop="email" label="邮箱" min-width="150" align="center" show-overflow-tooltip />
          <el-table-column prop="fax" label="传真" min-width="120" align="center" />
          <el-table-column prop="notes" label="备注" min-width="150" align="center" show-overflow-tooltip />
          <el-table-column label="操作" width="180" fixed="right" align="center">
            <template #default="scope">
              <div class="action-buttons">
                <el-button type="primary" size="small" @click="handleEdit(scope.row)" class="edit-btn" :icon="Edit">
                  编辑
                </el-button>
                <el-button type="danger" size="small" @click="handleDelete(scope.row.id)" class="delete-btn" :icon="Delete">
                  删除
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <el-pagination 
          v-model:current-page="paginationData.currentPage" 
          v-model:page-size="paginationData.pageSize" 
          :page-sizes="[10, 20, 50, 100]" 
          :total="paginationData.total" 
          layout="total, sizes, prev, pager, next, jumper" 
          @size-change="getTableData" 
          @current-change="getTableData"
          class="pagination"
        />
      </el-card>
    </div>

    <!-- 新增/编辑对话框 -->
    <sys-dialog 
      :title="dialog.title" 
      :width="dialog.width" 
      :visible="dialog.visible" 
      :height="dialog.height" 
      @onClose="closeDialog" 
      @onConfirm="submitForm"
      custom-class="customer-dialog"
    >
      <template #content>
        <el-form 
          :model="formData" 
          :rules="rules" 
          ref="formRef" 
          label-width="80px" 
          class="customer-form"
        >
          <el-card class="form-card" shadow="never">
            <template #header>
              <div class="form-header">
                <el-icon><Document /></el-icon>
                <span>基本信息</span>
              </div>
            </template>
            <div class="form-row">
              <el-form-item label="公司代码" prop="companyCode">
                <el-input v-model="formData.companyCode" placeholder="请输入公司代码" />
              </el-form-item>
              <el-form-item label="公司名称" prop="companyName">
                <el-input v-model="formData.companyName" placeholder="请输入公司名称" />
              </el-form-item>
            </div>
            <div class="form-row">
              <el-form-item label="联系人" prop="contactName">
                <el-input v-model="formData.contactName" placeholder="请输入联系人" />
              </el-form-item>
              <el-form-item label="联系电话" prop="contactPhone">
                <el-input v-model="formData.contactPhone" placeholder="请输入联系电话" />
              </el-form-item>
            </div>
            <div class="form-row">
              <el-form-item label="邮箱" prop="email">
                <el-input v-model="formData.email" placeholder="请输入邮箱" />
              </el-form-item>
              <el-form-item label="传真" prop="fax">
                <el-input v-model="formData.fax" placeholder="请输入传真" />
              </el-form-item>
            </div>
          </el-card>
          
          <el-card class="form-card" shadow="never">
            <template #header>
              <div class="form-header">
                <el-icon><Location /></el-icon>
                <span>地址信息</span>
              </div>
            </template>
            <div class="form-row single">
              <el-form-item label="地址" prop="address">
                <el-input v-model="formData.address" placeholder="请输入地址" />
              </el-form-item>
            </div>
          </el-card>
          
          <el-card class="form-card" shadow="never">
            <template #header>
              <div class="form-header">
                <el-icon><InfoFilled /></el-icon>
                <span>备注信息</span>
              </div>
            </template>
            <div class="form-row single">
              <el-form-item label="备注" prop="notes">
                <el-input 
                  v-model="formData.notes" 
                  type="textarea" 
                  :rows="3" 
                  placeholder="请输入备注信息" 
                />
              </el-form-item>
            </div>
          </el-card>
        </el-form>
      </template>
    </sys-dialog>
  </el-main>
</template>

<style scoped lang="scss">
.customer-main {
  padding: 0;
}

.main-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);
}

.search-card {
  margin-bottom: 20px;
  border-radius: 8px;
  transition: all 0.3s;
  
  :deep(.el-card__body) {
    padding: 15px 20px;
  }
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  
  .el-form-item {
    margin-bottom: 0;
    margin-right: 16px;
  }
  
  .search-buttons {
    margin-left: auto;
    
    .el-button {
      margin-left: 8px;
      transition: all 0.3s;
      
      &:first-child {
        margin-left: 0;
      }
    }
    
    .search-btn {
      background: linear-gradient(135deg, #1989fa, #0056b3);
      border: none;
      
      &:hover {
        opacity: 0.9;
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(25, 137, 250, 0.3);
      }
    }
    
    .add-btn {
      background: linear-gradient(135deg, #67c23a, #409eff);
      border: none;
      
      &:hover {
        opacity: 0.9;
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(103, 194, 58, 0.3);
      }
    }
    
    .reset-btn:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 12px rgba(144, 147, 153, 0.2);
    }
  }
}

.table-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  margin-bottom: 0;
  
  :deep(.el-card__body) {
    padding: 0;
    height: 100%;
    display: flex;
    flex-direction: column;
  }
}

.data-table {
  border-radius: 4px;
  flex: 1;
  
  :deep(.el-table__header-wrapper) {
    th {
      background-color: #f2f6fc;
      font-weight: 600;
    }
  }
  
  :deep(.el-table__row) {
    &:hover {
      td {
        background-color: #ecf5ff;
      }
    }
  }
  
  .action-buttons {
    display: flex;
    justify-content: center;
    
    .el-button {
      padding: 6px 10px;
      transition: all 0.3s;
      
      &:hover {
        transform: translateY(-2px);
      }
    }
    
    .edit-btn {
      margin-right: 10px;
    }
  }
}

.pagination {
  padding: 15px 20px;
  justify-content: flex-end;
  background: #fff;
  border-radius: 0 0 8px 8px;
}

.customer-form {
  padding: 20px;

  .form-card {
    margin-bottom: 15px;
    border-radius: 8px;
    transition: all 0.3s;
    overflow: hidden;
    border: 1px solid #ebeef5;
    
    &:last-child {
      margin-bottom: 0;
    }
    
    :deep(.el-card__header) {
      padding: 10px 15px;
      background: linear-gradient(90deg, #f0f9eb, #e1f3d8);
      border-bottom: 1px solid #e1f3d8;
    }
    
    .form-header {
      font-size: 16px;
      font-weight: 600;
      color: #67c23a;
      display: flex;
      align-items: center;
      gap: 8px;
      
      .el-icon {
        color: #67c23a;
      }
    }
  }

  .form-row {
    display: flex;
    gap: 20px;
    margin-bottom: 20px;

    &:last-child {
      margin-bottom: 0;
    }

    &.single {
      display: block;
    }

    :deep(.el-form-item) {
      flex: 1;
      margin-bottom: 0;

      .el-form-item__content {
        width: 100%;

        .el-input {
          width: 100%;
        }
      }
    }
  }
  
  :deep(.el-input__wrapper), :deep(.el-textarea__inner) {
    box-shadow: 0 0 0 1px #dcdfe6 inset;
    
    &:hover {
      box-shadow: 0 0 0 1px #c0c4cc inset;
    }
    
    &.is-focus {
      box-shadow: 0 0 0 1px #67c23a inset;
    }
  }
  
  :deep(.el-form-item__label) {
    font-weight: 500;
  }
}

:deep(.customer-dialog) {
  border-radius: 8px;
  overflow: hidden;
  
  .el-dialog__header {
    padding: 15px 20px;
    margin: 0;
    background: linear-gradient(90deg, #f0f9eb, #e1f3d8);
    border-bottom: 1px solid #e1f3d8;
    
    .el-dialog__title {
      font-size: 16px;
      font-weight: 600;
      color: #67c23a;
    }
    
    .el-dialog__headerbtn {
      top: 15px;
    }
  }
  
  .el-dialog__body {
    padding: 0;
  }
  
  .el-dialog__footer {
    padding: 10px 20px;
    border-top: 1px solid #ebeef5;
    background-color: #f5f7fa;
    
    .el-button {
      padding: 8px 20px;
      border-radius: 4px;
      transition: all 0.3s;
      
      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
      }
    }
  }
}
</style>
